package com.example.springbootminiodemo.service.impl;

import com.example.springbootminiodemo.common.beans.MinioBean;
import com.example.springbootminiodemo.entity.AddDocumentVo;
import com.example.springbootminiodemo.entity.DocumentInfo;
import com.example.springbootminiodemo.mapper.DocumentMapper;
import com.example.springbootminiodemo.service.DocumentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

@Service
public class DocumentServiceImpl implements DocumentService {
  
  
  private static final String BUCKET_NAME = "training";
  
  
  @Autowired
  private DocumentMapper documentMapper;
  @Autowired
  private MinioBean minioBean;
  
  /**
   * 表示用来添加文档信息
   *
   * @param addDocumentVo 传递的entity 对象
   * @return
   */
  @Override
  public DocumentInfo addDocument(AddDocumentVo addDocumentVo) throws Exception {
    String uploadUser = addDocumentVo.getUploadUser();
    MultipartFile file = addDocumentVo.getFile();
    
    // 直接创建桶
    minioBean.createBucket(BUCKET_NAME);
    
    // 开始获取文件名称
    String originalFilename = file.getOriginalFilename();
    // 表示新的文件名称
    StringBuffer newFileName = new StringBuffer();
    int locationIndex = originalFilename.lastIndexOf(".");
    String suffix = originalFilename.substring(locationIndex);
    
    
    // 通过构建的形式  构建新的文件名称
    newFileName.append(UUID.randomUUID());
    newFileName.append("_");
    newFileName.append(uploadUser);
    newFileName.append("_");
    newFileName.append(System.currentTimeMillis());
    newFileName.append(suffix);
    
    // 将文件放到桶中
    String visitUrl = minioBean.uploadFile(BUCKET_NAME, file, uploadUser + "/" + newFileName.toString());
    
    DocumentInfo documentInfo = new DocumentInfo();
    documentInfo.setUrl(visitUrl);
    documentInfo.setUploadUser(uploadUser);
    
    int insert = documentMapper.insert(documentInfo);
    if (insert > 0) return documentInfo;
    return null;
  }
}
